package com.sgb.kjwl.view.ui.activity.self.shop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityShopCompanyInfoBinding;
import com.sgb.kjwl.di.shopping.DaggerShopComponent;
import com.sgb.kjwl.di.shopping.ShopModule;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.CategoryChildEntity;
import com.sgb.kjwl.model.entity.user.CategoryParentsEntity;
import com.sgb.kjwl.model.entity.user.TalentTypeEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.ReceiptInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.BankInfoActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.ShowImgAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.MainBusinessPopWindow;
import com.sgb.kjwl.viewmodel.shopping.ShopConmpanyInfoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

import static androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL;

public class CompanyShopInfoActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private ActivityShopCompanyInfoBinding binding;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int LOGO = 10;
    private boolean isLoaded = false;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    //主营业务列表
    private List<CategoryParentsEntity<List<CategoryChildEntity>>> categoryParentsEntityList;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    //---------------logo------------------
    private List<LocalMedia> logLocal;
    private List<File> logFile;
    private List<String> logoUrls;
    //---------------公司图片----------------

    //图片上传
    private List<LocalMedia> selectList = new ArrayList<>();
    private ImageAdapter adapter;
    private List<String> urls;
    private List<File> fileList;
    public int imgTotal;
    private int currentImgNum;
    private List<String> uploadImgList = new ArrayList<>();

    private List<LocalMedia> companyLocal;
    //---------------证书-------------------
    private List<String> certificateUrls;
    private List<LocalMedia> certificateLocal;
    //---------------视频-------------------
    private List<LocalMedia> videoLocal;
    //-------------测试数据------------------
    private List<String> test;
    private int type;
    private Intent intent;
    private ImageAdapter showCompanyImgAdapter;
    private ShowImgAdapter showCertificateImgAdapter;
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private MainBusinessPopWindow mainBusinessPopWindow;
    private Map map;
    private String shopId;
    @Inject
    ShopConmpanyInfoModel viewModel;

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, CompanyShopInfoActivity.class);
        intent.putExtra("id", id);
        intent.setClass(context, CompanyShopInfoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerShopComponent.builder()
                .appComponent(appComponent)
                .shopModule(new ShopModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);


    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(CompanyShopInfoActivity.this, R.layout.activity_shop_company_info);
        binding.setViewModel(viewModel);

        binding.companyPhotoLl.setOnClickListener(this);
        binding.certificateLl.setOnClickListener(this);
        binding.videoLl.setOnClickListener(this);
        binding.openShop.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.backView.setOnClickListener(this);
        binding.llAddress.setOnClickListener(this);
        binding.llTicket.setOnClickListener(this);
        binding.llAccount.setOnClickListener(this);
        //设置联系电话智能输入数字
        binding.etMobile.setInputType(InputType.TYPE_CLASS_NUMBER);

        //企业图片adapter
        showCompanyImgAdapter = new ImageAdapter(this, null, null, 5);
        binding.companyPhotoRecycler.setLayoutManager(new GridLayoutManager(CompanyShopInfoActivity.this, 4));
        binding.companyPhotoRecycler.setAdapter(showCompanyImgAdapter);

        //证书图片adapter
        showCertificateImgAdapter = new ShowImgAdapter(this, null, null);
        binding.certificateRecycler.setLayoutManager(new LinearLayoutManager(CompanyShopInfoActivity.this, HORIZONTAL, false));
        binding.certificateRecycler.setAdapter(showCertificateImgAdapter);

        //主营业务POP Window
        mainBusinessPopWindow = new MainBusinessPopWindow(CompanyShopInfoActivity.this);
        mainBusinessPopWindow.setBgView(binding.grayLayout);
        mainBusinessPopWindow.setOnResultClick((key1, key2, key3) -> {
            List<TalentTypeEntity> talentTypeChildList = (List<TalentTypeEntity>) key1;
        });
        tesyDate();
    }

    @Override
    protected void init() {
        shopId = getIntent().getStringExtra("id");
        SharedPreferenceUtil.init(this);
        map = new HashMap();
        map.put("id", shopId);
        //城2、3级市列表
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        //----------logo图片用到的list
        logoUrls = new ArrayList<>();
        logFile = new ArrayList<>();
        //企业图片list
        urls = new ArrayList<>();
        fileList = new ArrayList<>();
        //相关证书list
        certificateUrls = new ArrayList<>();
        categoryParentsEntityList = new ArrayList<>();
        viewModel.shopDetail(map);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(String event) {
        if ("REFRESH_COMPANY_INFO".equals(event)) {
            viewModel.shopDetail(map);
            EventBus.getDefault().removeStickyEvent("REFRESH_COMPANY_INFO");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                finish();
                break;
            case R.id.next_view:
                viewModel.shopInfoEntity.get().setMainBusinessIds(binding.etBusiness.getText().toString());
                viewModel.shopInfoEntity.get().setIntroduction(binding.etIntroduce.getText().toString());

                if (showCompanyImgAdapter.getFileList().size() != 0) {
                    imgTotal = showCompanyImgAdapter.getFileList().size();
                    viewModel.uploadMutiFileModel(showCompanyImgAdapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
                } else {
                    uploadImgSuccess(showCompanyImgAdapter.getUrls(), 1);
                }
                break;

            case R.id.select_img:
                openPhotoView(0, logoUrls);
                break;
            case R.id.ll_address:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
            case R.id.open_shop:
//                ShopInfoActivity.start(CompanyShopInfoActivity.this, shopId);
                break;
            case R.id.ll_ticket:
                BankInfoActivity.start(CompanyShopInfoActivity.this);
                break;
            case R.id.ll_account:
                ReceiptInfoActivity.start(CompanyShopInfoActivity.this);
                break;
           /* case R.id.company_photo_ll:
                if (companyUrls.size() != 0) {
                    EventBus.getDefault().postSticky(ShopImageEvent.make().setMessageTag(EventConstant.EVENT_SHOP_COMPANY_RE_IMG).setMessageData(companyUrls).setObject(companyLocal));
                }
                SelectCompanyImageActivity.start(this, "企业照片", 0);
                break;
            case R.id.certificate_ll:
                if (certificateUrls.size() != 0) {
                    EventBus.getDefault().postSticky(ShopImageEvent.make().setMessageTag(EventConstant.EVENT_SHOP_CERTIFICATE_RE_IMG).setMessageData(certificateUrls).setObject(certificateLocal));
                }
                SelectCompanyImageActivity.start(this, "相关证书", 1);
                break;
            case R.id.video_ll:
                if (videoLocal != null) {
                    EventBus.getDefault().postSticky(ShopImageEvent.make().setMessageTag(EventConstant.EVENT_SHOP_COMPANY_RE_VIDEO).setMessageData(videoLocal));
                }
                SelectCompanyImageActivity.start(this, "企业视频", 2);
                break;*/
        }
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(showCompanyImgAdapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        }
    }

    //图片上传成功回调
    public void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        ArrayList<String> urlList = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            urlList.add(urls.get(i));
        }

        //todo 暂时注释
        if (type == 0) {
            if (viewModel.shopInfoEntity.get().getImage() != null) {
                viewModel.shopInfoEntity.get().getImage().addAll(urlList);
                urlList.clear();
                urlList.addAll(viewModel.shopInfoEntity.get().getImage());
            }
        }
        viewModel.shopInfoEntity.get().setImage(urlList);
        viewModel.saveShopInfo();
    }


    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_re_phone:
                break;
            case R.id.itv_edit_pw:
                break;
            /*case R.id.item_tv_brief_introduction_to_enterprises:
                CompanyBriefIntroductionActivity.start(this, binding.itemTvBriefIntroductionToEnterprises.getContent());
                break;*/
            case R.id.ll_address:

                break;

        }
    }

    /*@Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ShopEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SHOP_COMPANY_INFO) {
            binding.itemTvBriefIntroductionToEnterprises.setContent((String) event.getMessageData());
        } else if (event.getMessageTag() == EventConstant.EVENT_SHOP_COMPANY_IMG) {
            binding.companyPhotoRecycler.setVisibility(View.VISIBLE);
            companyUrls = (List<String>) event.getMessageData();
            companyLocal = (List<LocalMedia>) event.getObject();
            showCompanyImgAdapter.setDatas(companyUrls);
        } else if (event.getMessageTag() == EventConstant.EVENT_SHOP_CERTIFICATE_IMG) {
            binding.certificateRecycler.setVisibility(View.VISIBLE);
            certificateUrls = (List<String>) event.getMessageData();
            certificateLocal = (List<LocalMedia>) event.getObject();
            showCertificateImgAdapter.setDatas(certificateUrls);
        } else if (event.getMessageTag() == EventConstant.EVENT_SHOP_COMPANY_VIDEO) {
            videoLocal = (List<LocalMedia>) event.getMessageData();
            if (videoLocal != null) {
                binding.videoView.setVisibility(View.VISIBLE);
                binding.videoView.setUp(videoLocal.get(0).getRealPath(), JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "企业视频");
            }
        }
        EventBus.getDefault().removeStickyEvent(event);
    }*/

    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    fileList.clear();
                    urls.clear();
                    for (LocalMedia localMedia : selectList) {
                        File file = new File(localMedia.getRealPath());
                        fileList.add(file);
                        urls.add(localMedia.getRealPath());
                    }
                    showCompanyImgAdapter.setDatas(selectList, urls);
                    showCompanyImgAdapter.setFileList(fileList);
                    break;
            }
        }
    }

    private void tesyDate() {
        test = new ArrayList<>();
        test.add("Ak-47");
        test.add("M4A1-A");
        test.add("98-K");
        test.add("RPG");
        test.add("AWM");
        mainBusinessPopWindow.setData(test, false);
    }

    public void category(List<CategoryParentsEntity<List<CategoryChildEntity>>> categoryParentsEntityList) {
        this.categoryParentsEntityList = categoryParentsEntityList;
    }

    public void showCityPop() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            if (addressEntityList.get(i).getId().equals(viewModel.shopInfoEntity.get().getProvinceNo())) {
                cityPosition1 = i;
                break;
            }
        }

        for (int i = 0; i < addressEntityList.get(cityPosition1).getChildren().size(); i++) {
            if (addressEntityList.get(cityPosition1).getChildren().get(i).getId().equals(viewModel.shopInfoEntity.get().getCityNo())) {
                cityPosition2 = i;
                break;
            }
        }

        for (int i = 0; i < addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().size(); i++) {
            if (addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(i).getId().equals(viewModel.shopInfoEntity.get().getAreaNo())) {
                cityPosition3 = i;
                break;
            }
        }

        //条件选择器
        CityPickView cityOption = new CityPickBuilder(CompanyShopInfoActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.tvCity.setText(content);
            cityPosition1 = options1;
            cityPosition2 = options2;

            viewModel.shopInfoEntity.get().setProvinceNo(addressEntityList.get(options1).getNo());
            viewModel.shopInfoEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
            viewModel.shopInfoEntity.get().setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> entity : addressEntityList) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(entity.getChildren());
            for (int i = 0; i < entity.getChildren().size(); i++) {
                cityList.add(entity.getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (entity.getChildren().get(i).getChildren() == null
                        || entity.getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(entity.getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public void openImg(int selectModel, int type) {
        this.type = type;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(selectModel)
                .selectionMedia(logLocal)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    //预览
    private void openPhotoView(int position, List<String> urls) {
        if (intent == null) {
            intent = new Intent();
        }
        intent.setClass(this, PhotoViewActivity.class);
        intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) urls);
        intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
        startActivity(intent);
    }

    public void setData() {
        if ("0".equals(viewModel.shopInfoEntity.get().getInvoiceInfo())) {
            binding.tvTicketStatus.setText("未完善");
        } else {
            binding.tvTicketStatus.setText("已完善");
        }

        if ("0".equals(viewModel.shopInfoEntity.get().getReceiptInfo())) {
            binding.tvAccountStatus.setText("未完善");
        } else {
            binding.tvAccountStatus.setText("已完善");
        }

        if (!TextUtils.isEmpty(viewModel.shopInfoEntity.get().getAddress())) {
            binding.tvCity.setText(viewModel.shopInfoEntity.get().getAddress());
        }

        if (viewModel.shopInfoEntity.get().getImage().size() > 0) {
            showCompanyImgAdapter.getUrls().clear();
            showCompanyImgAdapter.setNetImgList(viewModel.shopInfoEntity.get().getImage());
        }
        binding.companyPhotoRecycler.setVisibility(View.VISIBLE);
    }
}
